package com.banksoft.cps.service.impl;

import com.banksoft.cps.bean.*;
import com.banksoft.cps.bean.common.ServiceException;
import com.banksoft.cps.bean.http.request.Request;
import com.banksoft.cps.bean.http.response.BaseData;
import com.banksoft.cps.bean.http.response.RowData;
import com.banksoft.cps.bean.query.*;
import com.banksoft.cps.bean.warpper.*;
import com.banksoft.cps.constants.ErrorConstant;
import com.banksoft.cps.dao.*;
import com.banksoft.cps.enums.TimeUnit;
import com.banksoft.cps.service.StatisticsService;
import com.banksoft.cps.util.*;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by rongzhao.zhu on 2018/1/16.
 */
@Service
public class StatisticsServiceImpl implements StatisticsService {


    @Autowired
    DeviceDao deviceDao;
    @Autowired
    CompanyDao companyDao;
    @Autowired
    MonitorProductDao monitorProductDao;
    @Autowired
    SaleOrderDao saleOrderDao;
    @Autowired
    MonitorValueDao monitorValueDao;
    @Autowired
    OffsetOrderDao offsetOrderDao;
    @Autowired
    MonitorValueImportDao monitorValueImportDao;
    @Autowired
    MonitorValueLoraDao monitorValueLoraDao;
    @Autowired
    LoraValueJjllDao loraValueJjllDao;
    @Autowired
    SupplierOrderDao supplierOrderDao;
    @Autowired
    MaterialDao materialDao;

    /**
     * 拉取远程的数据
     * 按照  产品类型和公司分组统计数据
     *
     * @param query
     * @return
     * @throws ServiceException
     */
    @Override
    public StatisticsWarpper query(StatisticsQuery query) throws ServiceException {
        StatisticsWarpper warpper = new StatisticsWarpper();
        DeviceQuery deviceQuery = new DeviceQuery();
        deviceQuery.setCompanyId(query.getCompanyId());
        deviceQuery.setProductId(query.getProductId());

        List<Device> devices = deviceDao.list(deviceQuery);

        List<String> companyIdList = new ArrayList<>();
        List<String> productIdList = new ArrayList<>();
        List<String> deviceIdList = new ArrayList<>();
        Map<String,Company> companyMap = new HashMap<>();
        Map<String,MonitorProduct> productMap = new HashMap<>();
        Map<String,OffsetOrder> offsetOrderMap = new HashMap<>();
        devices.stream().filter(d-> StringUtils.isNotBlank(d.getSensorId())&&StringUtils.isNotBlank(d.getUserId())).forEach(d->{
            if(StringUtils.isNotBlank(d.getCompanyId()) && !companyIdList.contains(d.getCompanyId())){
                companyIdList.add(d.getCompanyId());
            }
            if(StringUtils.isNotBlank(d.getProductId())&& !productIdList.contains(d.getProductId())){
                productIdList.add(d.getProductId());
            }
            deviceIdList.add(d.getId());
        });
        long timeB = 0;
        long timeE = 0;
        try{
            if(StringUtils.isNotBlank(query.getTimeBegin())){
                timeB = DateUtil.getTime2(query.getTimeBegin());
            }
            if(StringUtils.isNotBlank(query.getTimeEnd())){
                timeE = DateUtil.getTime2(query.getTimeEnd());
            }
        }catch (Exception e){
            throw new ServiceException(ErrorConstant.ec_param_error,ErrorConstant.em_date_error);
        }
        List<SaleOrder>  saleOrders  = saleOrderDao.listByDeviceIdList(deviceIdList,timeB,timeE);
        Map<String,MonitorValue> monitorValueMap = new HashMap<>();
        List<String> saleOrderIdList = saleOrders.stream().map(e->e.getId()).collect(Collectors.toList());
        if(!saleOrderIdList.isEmpty()){
            List<MonitorValue>  monitorValues = monitorValueDao.listBySaleOrderIdList(saleOrderIdList );
            List<OffsetOrder>  offsetOrders  = offsetOrderDao.listBySaleOrderIdList(saleOrderIdList);
            if(!monitorValues.isEmpty()){
                monitorValues.forEach(e->{
                    monitorValueMap.put(e.getSaleOrderId(),e);
                });
            }
            if(!offsetOrders.isEmpty()){
                offsetOrders.forEach(e->{
                    offsetOrderMap.put(e.getSaleOrderId(),e);
                });
            }
        }

        List<SaleOrderWarpper> saleOrderWarppers =  saleOrders.stream().map(e->{
            SaleOrderWarpper w =  new SaleOrderWarpper() ;
            BeanUtils.copyProperties(e,w);
            MonitorValue monitorValue= monitorValueMap.get(e.getId());
            OffsetOrder offsetOrder = offsetOrderMap.get(e.getId());
            w.setOffsetOrder(offsetOrder);
            w.setMonitorValue(monitorValue);
            return w;
        }).collect(Collectors.toList());
        //获取企业和产品信息
        if(!companyIdList.isEmpty()){
            List<Company> companies  = companyDao.listByIdList(companyIdList);
            companies.forEach(c->companyMap.put(c.getId(),c));
        }
        if(!productIdList.isEmpty()){
            List<MonitorProduct> products =  monitorProductDao.listByIdList(productIdList);
            products.forEach(p->productMap.put(p.getId(),p));
        }

        Map<String,Statistics> statisticsMap = new HashMap<>();
        if(!devices.isEmpty()){
            for(Device device:devices){
                if(StringUtils.isBlank(device.getSensorId())||StringUtils.isBlank(device.getUserId())){
                    continue;
                }
                Request request = PullDataUtil.buildRequest(query.getTimeBegin(),query.getTimeEnd(),device);
                request.setPage("1");
                request.setPageSize("1");
                String param =  JsonUtils.encode(request);
                String  result = HttpClientUtil.sendHttpPostJson(PullDataUtil.url, param);
                if(PullDataUtil.requestFail.equals(result)){
                    continue;
                }
                BaseData baseDataE = JsonUtils.decode(result, BaseData.class);
                if(PullDataUtil.pullOk.equals(baseDataE.getFlag())){
                    request.setPage(baseDataE.getTotalPage());
                    param =  JsonUtils.encode(request);
                    result = HttpClientUtil.sendHttpPostJson(PullDataUtil.url, param);
                    BaseData baseDataB = JsonUtils.decode(result, BaseData.class);
                    if(PullDataUtil.pullOk.equals(baseDataB.getFlag())) {
                        RowData rowDataE = baseDataE.getDataList().get(0);
                        RowData rowDataB = baseDataB.getDataList().get(0);
                        String val = StringNumber.sub(rowDataE.getVal(), rowDataB.getVal());
                        String mapKey = device.getCompanyId()+"-"+device.getProductId();
                        Statistics _statistics = statisticsMap.get(mapKey);
                        if(_statistics == null ){
                            _statistics  = new Statistics();
                            statisticsMap.put(mapKey,_statistics);
                        }
                        _statistics.setCompanyId(device.getCompanyId());
                        _statistics.setProductId(device.getProductId());
                        Company company = companyMap.get(device.getCompanyId());
                        _statistics.setCompanyName(company ==null?"":company.getName());
                        MonitorProduct product = productMap.get(device.getProductId());
                        _statistics.setProductName(product ==null?"":product.getName());
                        _statistics.setMonitorVal(val);
                        String amount = getAmount(saleOrders,device.getProductId(),device.getCompanyId());
                        _statistics.setAmount(amount);
                    }
                }else {
                    throw new ServiceException(ErrorConstant.ec_pull_error,ErrorConstant.em_pull_error);
                }
            }
            StatisticsSummary summary = new StatisticsSummary();
            summary.setAmount("0");
            summary.setMonitorVal("0");

            List<Statistics> statisticsList = new ArrayList<>(statisticsMap.values());

            statisticsList.forEach(e->{
                summary.setAmount(StringNumber.add(summary.getAmount(),e.getAmount()));
                summary.setMonitorVal(StringNumber.add(summary.getMonitorVal(),e.getMonitorVal()));

                List<SaleOrderWarpper> saleOrderWarpperList = saleOrderWarppers.stream().filter(s->
                        e.getCompanyId().equals(s.getCompanyId())&& e.getProductId().equals(s.getProductId()))
                        .collect(Collectors.toList());
                String  offsetVal= saleOrderWarpperList.stream().map(o-> o.getOffsetOrder()).filter(o->o !=null).map(o->o.getValue()).
                        reduce("0",(a,b)->StringNumber.add(a,b));
                e.setOffsetVal(offsetVal);
                summary.setOffsetVal(StringNumber.add(summary.getOffsetVal(),e.getOffsetVal()));
                e.setOrderList(saleOrderWarpperList);
            });
            warpper.setDataList(statisticsList);
            warpper.setSummary(summary);
        }
        return warpper;
    }

    @Override
    public List<StatisticsV2> queryV2(StatisticsQuery query) throws ServiceException {

        DeviceQuery deviceQuery = new DeviceQuery();
        deviceQuery.setCompanyId(query.getCompanyId());
        deviceQuery.setProductId(query.getProductId());

        List<Device> devices = deviceDao.list(deviceQuery);

        List<String> companyIdList = new ArrayList<>();
        List<String> productIdList = new ArrayList<>();
        List<String> deviceIdList = new ArrayList<>();
        Map<String,Company> companyMap = new HashMap<>();
        Map<String,MonitorProduct> productMap = new HashMap<>();
        devices.stream().filter(d-> StringUtils.isNotBlank(d.getSensorId())&&StringUtils.isNotBlank(d.getUserId())).forEach(d->{
            if(StringUtils.isNotBlank(d.getCompanyId()) && !companyIdList.contains(d.getCompanyId())){
                companyIdList.add(d.getCompanyId());
            }
            if(StringUtils.isNotBlank(d.getProductId())&& !productIdList.contains(d.getProductId())){
                productIdList.add(d.getProductId());
            }
            deviceIdList.add(d.getId());
        });
        long timeB = 0;
        long timeE = 0;
        try{
            if(StringUtils.isNotBlank(query.getTimeBegin())){
                timeB = DateUtil.getTime2(query.getTimeBegin());
            }
            if(StringUtils.isNotBlank(query.getTimeEnd())){
                timeE = DateUtil.getTime2(query.getTimeEnd());
            }
        }catch (Exception e){
            throw new ServiceException(ErrorConstant.ec_param_error,ErrorConstant.em_date_error);
        }
        List<SaleOrder>  saleOrders  = saleOrderDao.listByDeviceIdList(deviceIdList,timeB,timeE);
        List<MonitorValueImportWarpper> monitorValueImports = monitorValueImportDao.listByDeviceIdList(deviceIdList,timeB,timeE);
        List<String> saleOrderIdList = saleOrders.stream().map(e->e.getId()).collect(Collectors.toList());
        List<OffsetOrder>  offsetOrders = null;
        if(saleOrderIdList.isEmpty()){
            offsetOrders = new ArrayList<>();
        }else {
            offsetOrders = offsetOrderDao.listBySaleOrderIdList(saleOrderIdList);
        } 

        //获取企业和产品信息
        if(!companyIdList.isEmpty()){
            List<Company> companies  = companyDao.listByIdList(companyIdList);
            companies.forEach(c->companyMap.put(c.getId(),c));
        }
        if(!productIdList.isEmpty()){
            List<MonitorProduct> products =  monitorProductDao.listByIdList(productIdList);
            products.forEach(p->productMap.put(p.getId(),p));
        }
        Map<String,List<SaleOrder>> orderMap = saleOrders.stream().
                collect(Collectors.groupingBy(e->e.getDeviceId(),Collectors.toList()));
        Map<String,String> doMap = saleOrders.stream().collect(Collectors.toMap(e->e.getId(),e->e.getDeviceId()));
        Map<String,List<OffsetOrder>> offsetOrderMap = offsetOrders.stream().
                collect(Collectors.groupingBy(e->doMap.get(e.getSaleOrderId()),Collectors.toList()));
        Map<String,MonitorValueImportWarpper> mMap = monitorValueImports.stream().
                collect(Collectors.toMap(e->e.getDeviceId(),e->e));

        List<StatisticsV2> list = new ArrayList<>();
        devices.stream().forEach(e->{
            StatisticsV2 v2 =  new StatisticsV2();
            Company c =  companyMap.get(e.getCompanyId());
            MonitorProduct product = productMap.get(e.getProductId());
            v2.setCompany(c);
            v2.setMonitorProduct(product);
            List<SaleOrder>  _saleOrders =  orderMap.get(e.getId());
            List<OffsetOrder> _offsetOrders = offsetOrderMap.get(e.getId());
            MonitorValueImportWarpper warpper = mMap.get(e.getId());
            if(_saleOrders !=null ){
                v2.setSaleOrderValue(_saleOrders.stream().map(o->o.getAmount()).
                        reduce("0",(a,b)->StringNumber.add(a,b)));
            }else {
                v2.setSaleOrderValue("0");
            }
            if(_offsetOrders !=null ){
                v2.setOffsetValue(_offsetOrders.stream().map(o->o.getValue()).
                        reduce("0",(a,b)->StringNumber.add(a,b)));
            }else {
                v2.setOffsetValue("0");
            }


            if(warpper !=null ){
                v2.setMonitorValue(StringNumber.sub(warpper.getMaxValue(),warpper.getMinValue()));
            }else {
                v2.setMonitorValue("0");
            }
            list.add(v2);

        });
        return list;
    }

    @Override
    public List<StatisticsV2> queryV3(StatisticsQuery query) throws ServiceException {
        //查询符合条件的设备
        DeviceQuery deviceQuery = new DeviceQuery();
        deviceQuery.setCompanyId(query.getCompanyId());
        deviceQuery.setProductId(query.getProductId());
        List<Device> devices = deviceDao.list(deviceQuery);

        List<String> companyIdList = new ArrayList<>();
        List<String> productIdList = new ArrayList<>();
        List<String> deviceIdList = new ArrayList<>();
        Map<String,Company> companyMap = new HashMap<>();
        Map<String,MonitorProduct> productMap = new HashMap<>();
        devices.stream().forEach(d->{
            if(StringUtils.isNotBlank(d.getCompanyId()) && !companyIdList.contains(d.getCompanyId())){
                companyIdList.add(d.getCompanyId());
            }
            if(StringUtils.isNotBlank(d.getProductId())&& !productIdList.contains(d.getProductId())){
                productIdList.add(d.getProductId());
            }
            deviceIdList.add(d.getId());
        });


        //查询符合条件的销售单
        long timeB = 0;
        long timeE = 0;
        try{
            if(StringUtils.isNotBlank(query.getTimeBegin())){
                timeB = DateUtil.getTime2(query.getTimeBegin());
            }
            if(StringUtils.isNotBlank(query.getTimeEnd())){
                timeE = DateUtil.getTime2(query.getTimeEnd());
            }
        }catch (Exception e){
            throw new ServiceException(ErrorConstant.ec_param_error,ErrorConstant.em_date_error);
        }
        List<SaleOrder>  saleOrders  = saleOrderDao.listByDeviceIdList(deviceIdList,timeB,timeE);
        //查询对冲单
        List<String> saleOrderIdList = saleOrders.stream().map(e->e.getId()).collect(Collectors.toList());
        List<OffsetOrder>  offsetOrders = null;
        if(saleOrderIdList.isEmpty()){
            offsetOrders = new ArrayList<>();
        }else {
            offsetOrders = offsetOrderDao.listBySaleOrderIdList(saleOrderIdList);
        }
        //查询lora监控的订单
        List<MonitorValueLora> monitorValueLoras = null;
        if(saleOrderIdList.isEmpty()){
            monitorValueLoras = new ArrayList<>();
        }else {
            monitorValueLoras = monitorValueLoraDao.listBySaleOrderId(saleOrderIdList);
        }


        //获取企业和产品信息
        if(!companyIdList.isEmpty()){
            List<Company> companies  = companyDao.listByIdList(companyIdList);
            companies.forEach(c->companyMap.put(c.getId(),c));
        }
        if(!productIdList.isEmpty()){
            List<MonitorProduct> products =  monitorProductDao.listByIdList(productIdList);
            products.forEach(p->productMap.put(p.getId(),p));
        }
        Map<String,List<SaleOrder>> orderMap = saleOrders.stream().
                collect(Collectors.groupingBy(e->e.getDeviceId(),Collectors.toList()));
        Map<String,String> doMap = saleOrders.stream().collect(Collectors.toMap(e->e.getId(),e->e.getDeviceId()));
        Map<String,List<OffsetOrder>> offsetOrderMap = offsetOrders.stream().
                collect(Collectors.groupingBy(e->doMap.get(e.getSaleOrderId()),Collectors.toList()));

        Map<String,List<MonitorValueLora>> monitorValueLoraMap = monitorValueLoras.stream().
                collect(Collectors.groupingBy(e->doMap.get(e.getSaleOrderId()),Collectors.toList()));

        List<StatisticsV2> list = new ArrayList<>();
        devices.stream().forEach(e->{
            StatisticsV2 v2 =  new StatisticsV2();
            Company c =  companyMap.get(e.getCompanyId());
            MonitorProduct product = productMap.get(e.getProductId());
            v2.setCompany(c);
            v2.setMonitorProduct(product);
            List<SaleOrder>  _saleOrders =  orderMap.get(e.getId());
            List<OffsetOrder> _offsetOrders = offsetOrderMap.get(e.getId());
            List<MonitorValueLora> _monitorValueLoras = monitorValueLoraMap.get(e.getId());
            if(_saleOrders !=null ){
                v2.setSaleOrderValue(_saleOrders.stream().map(o->o.getAmount()).
                        reduce("0",(a,b)->StringNumber.add(a,b)));
            }else {
                v2.setSaleOrderValue("0");
            }
            if(_offsetOrders !=null ){
                v2.setOffsetValue(_offsetOrders.stream().map(o->o.getValue()).
                        reduce("0",(a,b)->StringNumber.add(a,b)));
            }else {
                v2.setOffsetValue("0");
            }
            if(_monitorValueLoras !=null ){
                v2.setMonitorValue(_monitorValueLoras.stream().map(o->StringNumber.mul(o.getValue(),o.getModulus())).
                        reduce("0",(a,b)->StringNumber.add(a,b)));
            }else {
                v2.setMonitorValue("0");
            }
            list.add(v2);

        });
        return list;
    }

    @Override
    public List<BaseStatistics> statistics(StatisticsCommonQuery query) throws ServiceException {
        //跟高斌沟通过，只能按照月份分组
        List<BaseStatistics> baseStatistics = new ArrayList<>();
        if(!TimeUnit.month.name().equals(query.getGroupBy())){
            return baseStatistics;
        }
        MonitorProduct monitorProduct= monitorProductDao.findById(query.getProductId());
        //这个地方先按照最后的系数去计算。不按照当时的系数计算。本身就是个估算值暂且这样计算。
        //因为混合产品统计也没有意义，所以必须限定产品类型
        if(StringUtils.isNotBlank(query.getProductId())&&StringUtils.isNotBlank(query.getCompanyId())){
            DeviceQuery deviceQuery = new DeviceQuery();
            deviceQuery.setCompanyId(query.getCompanyId());
            deviceQuery.setProductId(query.getProductId());
            List<Device> deviceList = deviceDao.list(deviceQuery);
            if(deviceList.isEmpty()){
                return null;
            }
            List<String> deveuiList = deviceList.stream().map(d->d.getDeveui()).collect(Collectors.toList());

            List<String> timeList = TimeUtil.buildFullList(query.getTimeBegin(),
                    query.getTimeEnd(),
                    TimeUnit.valueOf(query.getGroupBy()));
            timeList.forEach(e->{
                String timeBeginStr = e.replace('年','-').replace('月','-') +"01";
                long timebegin = DateUtil.getTime(timeBeginStr);
                long timeEnd = DateUtil.getAfterMonthTime(timebegin,1);
                List<LoraValueJjllWarpper> warppers =  loraValueJjllDao.listByDeveuiList(deveuiList,timebegin,timeEnd);
                String value= warppers.stream().collect(Collectors.reducing("0",
                        w->StringNumber.sub(w.getMaxValue(),w.getMinValue()),(a,b)->StringNumber.add(a,b)));
                BaseStatistics timeBaseStatistics = new BaseStatistics();
                timeBaseStatistics.setGroupBy(e);
                timeBaseStatistics.setValue(StringNumber.mul(value,monitorProduct.getModulus()));
                baseStatistics.add(timeBaseStatistics);
            });
        }
        return baseStatistics;
    }

    @Override
    public BaseStatisticsGroup statisticsSupplierOrders(StatisticsCommonQuery query) throws Exception {
        BaseStatisticsGroup result = new BaseStatisticsGroup();
        try{
            Map<String,List<BaseStatistics>> baseStatistics = new HashMap<>();
            result.setBaseStatistics(baseStatistics);
            List<String> productNames = new ArrayList<>();
            result.setLegendList(productNames);

            SupplierOrderQuery supplierOrderQuery = new SupplierOrderQuery();
            List<SupplierOrder> supplierOrders =  supplierOrderDao.list(supplierOrderQuery);

            supplierOrderQuery.setTimeB(DateUtil.getTime(query.getTimeBegin()));
            supplierOrderQuery.setTimeE(DateUtil.getTime(endTimeAddOne(query.getTimeEnd())));

            DecimalFormat df2 =new DecimalFormat("#.00");

            Map<String,List<SupplierOrder>> map = supplierOrders.stream().
                    collect(Collectors.groupingBy(e->e.getMaterialId(),Collectors.toList()));
            List<String> timeList = TimeUtil.buildFullList(query.getTimeBegin(),
                    query.getTimeEnd(),
                    TimeUnit.valueOf(query.getGroupBy()));
            result.setxAxis(timeList);
            List<Material> materials =  materialDao.list(new MaterialQuery());

            materials.forEach(e->{
                String  elementId = e.getId();
                productNames.add(e.getName());
                List<SupplierOrder> _supplierOrders =  map.get(elementId);
                Multimap<String,String> multimap = ArrayListMultimap.create();
                timeList.forEach(t->multimap.put(t,null));
                if(_supplierOrders == null){
                    baseStatistics.put(e.getName(),timeList.stream().map(t->{
                        BaseStatistics _statistics = new BaseStatistics();
                        _statistics.setValue("0");
                        return _statistics;
                    }).collect(Collectors.toList()));
                }else {
                    _supplierOrders.forEach(v->
                            multimap.put(TimeUtil.convert(v.getCreateTime(), TimeUnit.valueOf(query.getGroupBy())),v.getAmount()));
                    List<BaseStatistics> statistics = timeList.stream().map(t->{
                        BaseStatistics vo = new BaseStatistics();
                        vo.setGroupBy(t);
                        Collection<String> values = multimap.get(t);
                        List<String> vList =  values.stream().filter(s->s!=null).collect(Collectors.toList());
                        if(!vList.isEmpty()){
                            String val = df2.format(vList.stream().mapToDouble(s->Double.valueOf(s.replaceAll("[^\\d.]",""))).average().getAsDouble());
                            vo.setValue(val);
                        }else {
                            vo.setValue("0");
                        }
                        return vo;
                    }).collect(Collectors.toList());

                    baseStatistics.put(e.getName(),statistics);
                }

            });
        }catch (Exception e){
            e.printStackTrace();
        }


        return result;
    }

    @Override
    public BaseStatisticsGroup statisticsSaleOrders(StatisticsCommonQuery query) throws Exception {
        BaseStatisticsGroup result = new BaseStatisticsGroup();
        try{
            Map<String,List<BaseStatistics>> baseStatistics = new HashMap<>();
            result.setBaseStatistics(baseStatistics);
            List<String> productNames = new ArrayList<>();
            result.setLegendList(productNames);

            SaleOrderQuery supplierOrderQuery = new SaleOrderQuery();
            List<SaleOrder> saleOrders =  saleOrderDao.list(supplierOrderQuery);

            supplierOrderQuery.setTimeB(DateUtil.getTime(query.getTimeBegin()));
            supplierOrderQuery.setTimeE(DateUtil.getTime(endTimeAddOne(query.getTimeEnd())));

            DecimalFormat df2 =new DecimalFormat("#.00");

            Map<String,List<SaleOrder>> map = saleOrders.stream().
                    collect(Collectors.groupingBy(e->e.getProductId(),Collectors.toList()));
            List<String> timeList = TimeUtil.buildFullList(query.getTimeBegin(),
                    query.getTimeEnd(),
                    TimeUnit.valueOf(query.getGroupBy()));
            result.setxAxis(timeList);
            List<MonitorProduct> products =  monitorProductDao.list(new MonitorProductQuery());

            products.forEach(e->{
                String  elementId = e.getId();
                productNames.add(e.getName());
                List<SaleOrder> _saleOrders =  map.get(elementId);
                Multimap<String,String> multimap = ArrayListMultimap.create();
                timeList.forEach(t->multimap.put(t,null));
                if(_saleOrders == null){
                    baseStatistics.put(e.getName(),timeList.stream().map(t->{
                        BaseStatistics _statistics = new BaseStatistics();
                        _statistics.setValue("0");
                        return _statistics;
                    }).collect(Collectors.toList()));
                }else {
                    _saleOrders.forEach(v->
                            multimap.put(TimeUtil.convert(v.getCreateTime(), TimeUnit.valueOf(query.getGroupBy())),v.getAmount()));
                    List<BaseStatistics> statistics = timeList.stream().map(t->{
                        BaseStatistics vo = new BaseStatistics();
                        vo.setGroupBy(t);
                        Collection<String> values = multimap.get(t);
                        List<String> vList =  values.stream().filter(s->s!=null).collect(Collectors.toList());
                        if(!vList.isEmpty()){
                            String val = df2.format(vList.stream().mapToDouble(s->Double.valueOf(s.replaceAll("[^\\d.]",""))).average().getAsDouble());
                            vo.setValue(val);
                        }else {
                            vo.setValue("0");
                        }
                        return vo;
                    }).collect(Collectors.toList());

                    baseStatistics.put(e.getName(),statistics);
                }

            });
        }catch (Exception e){
            e.printStackTrace();

        }
        return result;
    }

    private String getAmount(List<SaleOrder> saleOrders, String productId, String companyId){
        String amount  = saleOrders.stream().filter(s->{
            boolean flag = true;
            if(StringUtils.isNotBlank(companyId)){
                flag = flag && companyId.equals(s.getCompanyId());

            }
            if(StringUtils.isNotBlank(productId)){
                flag = flag && productId.equals(s.getProductId());
            }
            return flag;
        }).map(e->e.getAmount()).reduce("0",(a,b)->StringNumber.add(a,b));
        return amount;
    }
    private String endTimeAddOne(String endTime){
        return  DateUtil.getDateStringByFormat(DateUtil.getAfterDayTime(DateUtil.getTime(endTime),1),
                "yyyy-MM-dd");
    }
}
